iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 5
0
AI & Data

Python&ML資料分析系列 第 5

【Day 5】Python 迴圈語法練習

  • 分享至 

  • xImage
  •  

1、輸入一個整數,求其逆序數
```
def reversed1(number):
length = len(number)
out = ''
for i in range(len(number)):
out += number[length - 1 - i]
return out

def reversed2(number):
    number = int(number)
    out = 0
    while number != 0:
        out = out * 10 + number % 10
        number = number // 10
    return out


if __name__ == '__main__':
    number = input('input a number:')
    out1 = reversed1(number)
    out2 = reversed2(number)
    print(out1)
    print(out2)
    ```

2、將一個正整數分解質因數

 def sp1(number):
 start = str(number)
 out = []
 i = 2
 while number != 1:
     while number % i == 0:
         number //= i
         out.append(str(i))
     i += 1
 print(start + '=' + '*'.join(out))


 def sp2(number):
     print(str(number) + '=', end='')
     i = 2
     while number != 1:
         while number % i ==0:
             number //= i
             if number == 1:
                 print('{:d}'.format(i), end='')
             else:
                 print('{:d}*'.format(i), end='')
         i += 1


 if __name__ == '__main__':
     number = eval(input('input a number:'))
     sp1(number)
     sp2(number)
     ```

上一篇
【Day 4】Python if語法練習
下一篇
【Day6】Python函數式
系列文
Python&ML資料分析17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言